package com.kingre.et.util;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.commons.lang.time.DateFormatUtils;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.kingre.et.action.DisReportAction;

public class ExportPDF {

    public static ByteArrayOutputStream getPDFStream(DisReportAction from) throws DocumentException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        Document doc = new Document(PageSize.A4, 72, 72, 52, 52);
        PdfWriter.getInstance(doc, baos);
        doc.open();

        try {

            doc.addAuthor("北京市教育人才培训中心");
            doc.addCreator("北京市教育人才培训中心");
            doc.addTitle("就业适应力测评报告");
            doc.addSubject("测评报告");
            doc.addCreationDate();

            BaseFont bfCN = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
            Font fontHead = new Font(bfCN, 18, Font.BOLD, BaseColor.BLACK);
            Font fontSubhead = new Font(bfCN, 14, Font.BOLD, BaseColor.BLACK);
            Font fontContext = new Font(bfCN, 10, Font.NORMAL, BaseColor.BLACK);
            Font fontContextBold = new Font(bfCN, 10, Font.BOLD, BaseColor.BLACK);
            Font fontContextSmall = new Font(bfCN, 9, Font.NORMAL, BaseColor.BLACK);

            Paragraph p = new Paragraph("《职业适应力测评》报告", fontHead);
            p.setAlignment(Element.TITLE);
            doc.add(p);

            doc.add(Chunk.NEWLINE);
            p = new Paragraph("个人信息", fontSubhead);
            p.setAlignment(Element.TITLE);
            doc.add(p);

            float[] widths = { 120f, 120f, 110f };
            PdfPTable table = new PdfPTable(widths);
            table.setSpacingBefore(10f);
            table.setTotalWidth(350f);
            table.setLockedWidth(true);
            PdfPCell cell = new PdfPCell(new Paragraph("姓名：" + from.getUser().getName(), fontContextSmall));
            cell.setFixedHeight(18);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph("性别：" + (from.getUser().getSex().intValue() == 10 ? "男" : "女"),
                    fontContextSmall));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph("年龄：" + from.getUser().getAge(), fontContextSmall));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph("学号：" + from.getUser().getStudentId(), fontContextSmall));
            cell.setFixedHeight(18);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("学历："
                    + (from.getUser().getDegree().intValue() == 10 ? "高职"
                            : (from.getUser().getDegree().intValue() == 20 ? "本科" : "研究生")), fontContextSmall));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph("年级："
                    + (from.getUser().getGrade().intValue() == 1 ? "一年级"
                            : (from.getUser().getGrade().intValue() == 2 ? "二年级" : (from.getUser().getGrade()
                                    .intValue() == 3 ? "三年级" : "四年级"))), fontContextSmall));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph("高校：" + from.getUser().getSchool().getOverSchool().getName(),
                    fontContextSmall));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph("院系：" + from.getUser().getSchool().getName(), fontContextSmall));
            cell.setFixedHeight(18);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
            String major = "";
            switch (from.getUser().getMajor().intValue()) {
            case 11:
                major = "哲学";
                break;
            case 12:
                major = "经济学";
                break;
            case 13:
                major = "法学";
                break;
            case 14:
                major = "教育学";
                break;
            case 15:
                major = "文学";
                break;
            case 16:
                major = "历史学";
                break;
            case 17:
                major = "理学";
                break;
            case 18:
                major = "工学";
                break;
            case 19:
                major = "农学";
                break;
            case 20:
                major = "医学";
                break;
            case 21:
                major = "军事学";
                break;
            case 22:
                major = "管理学";
                break;
            case 23:
                major = "艺术学";
                break;
            default:
                major = "其它";
            }
            cell = new PdfPCell(new Paragraph("专业：" + major, fontContextSmall));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph("生源地：" + (from.getUser().getSource().intValue() == 10 ? "在京生源" : "外地生源"),
                    fontContextSmall));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph("Email：" + from.getUser().getEmail(), fontContextSmall));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setColspan(2);
            table.addCell(cell);
            doc.add(table);

            doc.add(Chunk.NEWLINE);
            p = new Paragraph("综合得分", fontSubhead);
            p.setAlignment(Element.TITLE);
            doc.add(p);

            int imageHigh = 572;
            p = new Paragraph("职业适应力：" + from.getAdapScore() + " 分", fontContextBold);
            p.setFirstLineIndent(90f);
            p.setSpacingBefore(5f);
            Image img = Image.getInstance(from.getClass().getResource("/").getPath() + "../../images/score"
                    + from.getAdapScore() + ".PNG");
            img.setAlignment(Element.ALIGN_CENTER);
            img.scaleAbsolute(120, 12);
            img.setAbsolutePosition(250, imageHigh);
            p.add(img);
            doc.add(p);

            p = new Paragraph("保障力指数：" + from.getEnsureScore() + " 分", fontContextBold);
            p.setFirstLineIndent(90f);
            p.setSpacingBefore(5f);
            img = Image.getInstance(from.getClass().getResource("/").getPath() + "../../images/score"
                    + from.getEnsureScore() + ".PNG");
            img.setAlignment(Element.ALIGN_CENTER);
            img.scaleAbsolute(120, 12);
            img.setAbsolutePosition(250, imageHigh - 20);
            p.add(img);
            doc.add(p);

            p = new Paragraph("驱动力指数：" + from.getDriveScore() + " 分", fontContextBold);
            p.setFirstLineIndent(90f);
            p.setSpacingBefore(5f);
            img = Image.getInstance(from.getClass().getResource("/").getPath() + "../../images/score"
                    + from.getDriveScore() + ".PNG");
            img.setAlignment(Element.ALIGN_CENTER);
            img.scaleAbsolute(120, 12);
            img.setAbsolutePosition(250, imageHigh - 40);
            p.add(img);
            doc.add(p);

            p = new Paragraph("执行力指数：" + from.getExecuteScore() + " 分", fontContextBold);
            p.setFirstLineIndent(90f);
            p.setSpacingBefore(5f);
            img = Image.getInstance(from.getClass().getResource("/").getPath() + "../../images/score"
                    + from.getExecuteScore() + ".PNG");
            img.setAlignment(Element.ALIGN_CENTER);
            img.scaleAbsolute(120, 12);
            img.setAbsolutePosition(250, imageHigh - 60);
            p.add(img);
            doc.add(p);

            p = new Paragraph("报告真实度：" + from.getFlamScore() + " 分", fontContextBold);
            p.setFirstLineIndent(90f);
            p.setSpacingBefore(5f);
            img = Image.getInstance(from.getClass().getResource("/").getPath() + "../../images/score"
                    + from.getFlamScore() + ".PNG");
            img.setAlignment(Element.ALIGN_CENTER);
            img.scaleAbsolute(120, 12);
            img.setAbsolutePosition(250, imageHigh - 80);
            p.add(img);
            doc.add(p);

            if (from.getFlamScore() >= 7)
                p = new Paragraph("您在答题的时候完全按照自己的情况，本测评报告的具有很高的真实性。", fontContext);
            else if (from.getFlamScore() >= 4)
                p = new Paragraph("您在答题的时候能兼顾自己的真实的情况和社会的看法，测评报告真实性较好。", fontContext);
            else
                p = new Paragraph("您在答题的时候可能过于在意别人对自己的看法，没有按照自己的情况作答，测评报告的真实性可能不足。", fontContext);
            p.setFirstLineIndent(20f);
            p.setSpacingBefore(10f);
            doc.add(p);

            doc.add(Chunk.NEWLINE);
            p = new Paragraph("职业适应力", fontSubhead);
            p.setAlignment(Element.TITLE);
            doc.add(p);
            p = new Paragraph("职业适应力：" + from.getAdapScore() + " 分", fontContextBold);
            p.setFirstLineIndent(80f);
            p.setSpacingBefore(10f);
            img = Image.getInstance(from.getClass().getResource("/").getPath() + "../../images/score"
                    + from.getAdapScore() + ".PNG");
            img.setAlignment(Element.ALIGN_CENTER);
            img.scaleAbsolute(120, 12);
            // img.setAbsolutePosition(250, 552);
            p.add(img);
            doc.add(p);

            String path = System.getProperty("java.io.tmpdir");
            if (path.lastIndexOf('\\') != 0 || path.lastIndexOf('/') != 0) {
                if (path.indexOf('\\') >= 0)
                    path += "\\";
                else
                    path += "/";
            }
            img = Image.getInstance(path + from.getSpiderCharName());
            img.setAlignment(Element.ALIGN_CENTER);
            img.scaleAbsolute(300, 240);
            doc.add(img);
            p = new Paragraph(
                    from.getDimensioDes().length() < 90 ? (from.getDimensioDes() + "                                                                 ")
                            : from.getDimensioDes(), fontContext);
            p.setFirstLineIndent(20f);
            p.setSpacingBefore(10f);
            doc.add(p);

            imageHigh = 792;
            for (int i = 0; i < from.getDimensioScores().size(); i++) {
                if (i == 0 || i == 3 || i == 6) {
                    switch (i) {
                    case 0:
                        p = new Paragraph("保障力：" + from.getEnsureScore() + " 分", fontContextBold);
                        break;
                    case 3:
                        p = new Paragraph("驱动力：" + from.getDriveScore() + " 分", fontContextBold);
                        break;
                    case 6:
                        p = new Paragraph("执行力：" + from.getExecuteScore() + " 分", fontContextBold);
                    }
                    p.setFirstLineIndent(70f);
                    p.setSpacingBefore(5f);
                    doc.add(p);
                    imageHigh = imageHigh - 20;
                }
                p = new Paragraph(from.getDimensioScores().get(i).getDimensionality().getName() + "："
                        + from.getDimensioScores().get(i).getDimensionality().getDescription() + "    "
                        + from.getDimensioScores().get(i).getStandardScore() + "分", fontContextBold);
                p.setFirstLineIndent(70f);
                p.setSpacingBefore(5f);
                img = Image.getInstance(from.getClass().getResource("/").getPath() + "../../images/score"
                        + from.getDimensioScores().get(i).getStandardScore() + ".PNG");
                img.setAlignment(Element.ALIGN_CENTER);
                img.scaleAbsolute(120, 12);
                img.setAbsolutePosition(280, imageHigh);
                p.add(img);
                doc.add(p);

                imageHigh = imageHigh - 20;
            }

            String subTitle = "";
            for (int i = 0; i < from.getDimensioScores().size(); i++) {
                doc.add(Chunk.NEWLINE);
                switch (i) {
                case 0:
                    subTitle = "保障力一： ";
                    break;
                case 1:
                    subTitle = "保障力二： ";
                    break;
                case 2:
                    subTitle = "保障力三： ";
                    break;
                case 3:
                    subTitle = "驱动力一： ";
                    break;
                case 4:
                    subTitle = "驱动力二： ";
                    break;
                case 5:
                    subTitle = "驱动力三： ";
                    break;
                case 6:
                    subTitle = "执行力一： ";
                    break;
                case 7:
                    subTitle = "执行力二： ";
                    break;
                case 8:
                    subTitle = "执行力三： ";
                    break;
                }
                p = new Paragraph(subTitle + "： " + from.getDimensioScores().get(i).getDimensionality().getName(),
                        fontSubhead);
                p.setAlignment(Element.TITLE);
                doc.add(p);

                float[] sWidths = { 90f, 120f };
                table = new PdfPTable(sWidths);
                table.setSpacingBefore(10f);
                table.setSpacingAfter(10f);
                table.setTotalWidth(210f);
                table.setLockedWidth(true);

                cell = new PdfPCell(new Paragraph(from.getDimensioScores().get(i).getDimensionality().getName() + "："
                        + from.getDimensioScores().get(i).getStandardScore() + " 分", fontContextBold));
                cell.setVerticalAlignment(Element.ALIGN_RIGHT);
                cell.setBorder(0);
                cell.setFixedHeight(18);
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                table.addCell(cell);
                img = Image.getInstance(from.getClass().getResource("/").getPath() + "../../images/score"
                        + from.getDimensioScores().get(i).getStandardScore() + ".PNG");
                img.setAlignment(Element.ALIGN_LEFT);
                img.scaleAbsolute(120, 12);
                cell = new PdfPCell(img);
                cell.setBorder(0);
                cell.setFixedHeight(18);
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                table.addCell(cell);
                doc.add(table);
                String levelDis = "";
                if (from.getDimensioScores().get(i).getStandardScore() >= 9)
                    levelDis = "很高";
                else if (from.getDimensioScores().get(i).getStandardScore() >= 7)
                    levelDis = "较高";
                else if (from.getDimensioScores().get(i).getStandardScore() >= 5)
                    levelDis = "中等";
                else if (from.getDimensioScores().get(i).getStandardScore() >= 3)
                    levelDis = "较低";
                else
                    levelDis = "很低";

                p = new Paragraph("说明：得分" + levelDis + "，"
                        + from.getDimensioScores().get(i).getDimensionality().getName() + "在人群中处于" + levelDis + "水平。",
                        fontContext);
                p.setFirstLineIndent(20f);
                p.setSpacingBefore(0f);
                doc.add(p);
                p = new Paragraph(from.getDimensioScores().get(i).getDimensionality().getName() + "： "
                        + from.getText("dimen.description" + (i + 1)), fontContext);
                p.setFirstLineIndent(20f);
                p.setSpacingBefore(5f);
                doc.add(p);

                p = new Paragraph("", fontContext);
                p.setSpacingBefore(10f);
                switch (i) {
                case 0:
                    img = Image.getInstance(path + from.getBarChartName0());
                    break;
                case 1:
                    img = Image.getInstance(path + from.getBarChartName1());
                    break;
                case 2:
                    img = Image.getInstance(path + from.getBarChartName2());
                    break;
                case 3:
                    img = Image.getInstance(path + from.getBarChartName3());
                    break;
                case 4:
                    img = Image.getInstance(path + from.getBarChartName4());
                    break;
                case 5:
                    img = Image.getInstance(path + from.getBarChartName5());
                    break;
                case 6:
                    img = Image.getInstance(path + from.getBarChartName6());
                    break;
                case 7:
                    img = Image.getInstance(path + from.getBarChartName7());
                    break;
                case 8:
                    img = Image.getInstance(path + from.getBarChartName8());
                    break;
                }
                img.setAlignment(Element.ALIGN_CENTER);
                img.scaleAbsolute(300, 120);
                p.add(img);
                doc.add(p);

                // float[] tWidths = { 120f, 30f, 360f };
                float[] tWidths = { 120f, 390f };
                table = new PdfPTable(tWidths);
                table.setSpacingBefore(10f);
                table.setTotalWidth(510f);
                table.setLockedWidth(true);
                table.setSplitLate(true);
                table.setSplitRows(false);

                img = Image.getInstance(from.getClass().getResource("/").getPath() + "../../images/weidu" + (i + 1)
                        + ".PNG");
                img.setAlignment(Element.ALIGN_CENTER);
                img.scaleAbsolute(128, 120);
                cell = new PdfPCell(img);
                cell.setBorder(0);
                // cell.setRowspan(3);
                table.addCell(cell);

                float[] subWidths = { 30f, 360f };
                PdfPTable subTable = new PdfPTable(subWidths);

                String cellstr = "";
                for (int j = i * 9; j < (i + 1) * 9; j++) {
                    if (j == i * 9 || j == i * 9 + 3 || j == i * 9 + 6) {
                        cell = new PdfPCell(new Paragraph(from.getRawdatas().get(j).getTypeName(), fontContextBold));
                        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        cell.setBorder(0);
                        subTable.addCell(cell);
                        cellstr = "          处于" + from.getRawdatas().get(j).getLevelName() + "水平。";
                    }

                    if (from.getRawdatas().get(j).getStandardScore() >= 7)
                        cellstr += from.getRawdatas().get(j).getQuestion().getHigh();
                    else if (from.getRawdatas().get(j).getStandardScore() >= 4)
                        cellstr += from.getRawdatas().get(j).getQuestion().getMiddle();
                    else
                        cellstr += from.getRawdatas().get(j).getQuestion().getLow();
                    if (j % 3 == 2)
                        cellstr += "。";
                    else
                        cellstr += "；";
                    if (j == i * 9 + 2 || j == i * 9 + 5 || j == i * 9 + 8) {
                        cell = new PdfPCell(new Paragraph(cellstr, fontContextSmall));
                        cell.setLeading(12f, 0);
                        cell.setBorder(0);
                        subTable.addCell(cell);
                    }
                }
                cell = new PdfPCell(subTable);
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                cell.setBorder(0);
                table.addCell(cell);

                doc.add(table);
                p = new Paragraph("拓展建议：", fontContextBold);
                p.setFirstLineIndent(10f);
                p.setSpacingBefore(5f);
                doc.add(p);
                for (int j = 0, k = 1; j < from.getRawdatas().size(); j++) {
                    if (i == j / 9) {
                        if (from.getRawdatas().get(j).getStandardScore() <= 5) {
                            p = new Paragraph((k++) + ".    " + from.getRawdatas().get(j).getQuestion().getSuggest(),
                                    fontContext);
                            p.setFirstLineIndent(20f);
                            p.setSpacingBefore(5f);
                            doc.add(p);
                        }
                    }
                }
            }
            doc.add(Chunk.NEWLINE);
            p = new Paragraph("总结", fontSubhead);
            p.setAlignment(Element.TITLE);
            doc.add(p);
            p = new Paragraph(
                    "职业适应能力的培养，不是一朝一夕的事情，而是个思维逐渐调整、态度逐渐改变，习惯逐渐养成的过程。因此，必须贯穿于整个大学期间，在课堂、校园和各种社会实践中培养。这种培养的核心是改变在应试教育环境下形成的不适应职业环境的行为习惯，为成功步入职场和实现职业发展奠定基础。",
                    fontContext);
            p.setFirstLineIndent(20f);
            p.setSpacingBefore(5f);
            doc.add(p);

            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            p = new Paragraph("北京市教育人才培训中心", fontContext);
            p.setAlignment(Element.ALIGN_RIGHT);
            p.setSpacingBefore(5f);
            doc.add(p);
            p = new Paragraph(DateFormatUtils.format(new java.util.Date(), "yyyy-MM-dd"), fontContext);
            p.setAlignment(Element.ALIGN_RIGHT);
            p.setSpacingBefore(5f);
            doc.add(p);
        } catch (Exception e) {
            e.getStackTrace();
        } finally {
            doc.close();

        }

        return baos;
    }

    /**
     * @param args
     * @throws IOException
     * @throws FileNotFoundException
     */
    public static void main(String[] args) throws IOException {
        String path = "D:\\apache\\apache-tomcat-7.0.16\\temp";
        System.out.println(path);
        if (path.lastIndexOf('\\') != 0 || path.lastIndexOf('/') != 0) {
            if (path.indexOf('\\') >= 0)
                System.out.println(path + "\\");
            else
                System.out.println(path + "/");
        } else
            System.out.println(path);
    }

}
